import { createContext, useState, useContext, useEffect } from 'react';

// 创建Context
const FollowContext = createContext();

// 创建Provider组件
export function FollowProvider({ children }) {
  // 从本地存储加载关注状态
  const [followedUsers, setFollowedUsers] = useState(() => {
    const savedFollows = localStorage.getItem('followedUsers');
    return savedFollows ? JSON.parse(savedFollows) : [];
  });

  // 关注用户
  const followUser = (userId, username) => {
    setFollowedUsers(prev => {
      // 检查用户是否已经在关注列表中
      if (prev.some(user => user.id === userId)) {
        return prev;
      }
      // 添加用户到关注列表
      return [...prev, { id: userId, username, followedAt: new Date().toISOString() }];
    });
  };

  // 取消关注
  const unfollowUser = (userId) => {
    setFollowedUsers(prev => prev.filter(user => user.id !== userId));
  };

  // 检查用户是否被关注
  const isFollowing = (userId) => {
    return followedUsers.some(user => user.id === userId);
  };

  // 当followedUsers变化时，保存到本地存储
  useEffect(() => {
    localStorage.setItem('followedUsers', JSON.stringify(followedUsers));
  }, [followedUsers]);

  return (
    <FollowContext.Provider value={{ followedUsers, followUser, unfollowUser, isFollowing }}>
      {children}
    </FollowContext.Provider>
  );
}

// 自定义Hook，简化Context的使用
export function useFollow() {
  const context = useContext(FollowContext);
  if (!context) {
    throw new Error('useFollow must be used within a FollowProvider');
  }
  return context;
} 